package com.zwj.batch.config.test;

import com.zwj.batch.validators.NameParamValidator;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 作业增量参数 run.id
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2023-05-22 21:16:00
 */
//@Configuration
public class BatchConfig04 {
    //job构造工厂
    @Resource
    private JobBuilderFactory jobBuilderFactory;
    //step构造工厂
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    /**
     * 逻辑主体
     *
     * @return
     */
    @StepScope
    @Bean
    public Tasklet tasklet() {
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                Map<String, Object> jobParameters = chunkContext.getStepContext().getJobParameters();
                System.out.println("run.id = " + jobParameters.get("run.id"));
                return RepeatStatus.FINISHED;
            }
        };
    }

    @Bean
    public Job job() {
        return jobBuilderFactory.get("incr-params-job")//给job命名
                .start(step1())//具体执行什么步骤(step)
                .incrementer(new RunIdIncrementer())//保证参数自增，可以让一个job重复执行
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("incr-params-step")//给step命名
                .tasklet(tasklet())//注入具体要执行的逻辑
                .build();//构建
    }

    @Bean
    public NameParamValidator validator() {
        return new NameParamValidator();
    }
}
